
from flask import Flask, render_template, request
import pandas as pd
import cufflinks as cf
import plotly as py
import plotly.graph_objs as go


app = Flask(__name__)


df = pd.read_csv('hurun.csv', encoding='utf-8', delimiter="\t")
def read_data():
    return pd.read_csv("C:/Users/HP/Desktop/数据分析/week11/hurun_unicorn.tsv", encoding="utf8", sep="\t")
regions_available = list(df['行业'].dropna().unique())
regions_available_city = list(df['城市'].dropna().unique())
df_male = df.head()
cf.set_config_file(offline=True, theme="ggplot")
py.offline.init_notebook_mode()
@app.route('/')
@app.route('/hurun',methods=['GET'])
def hu_run_2019():
    data_str = df.to_html()
    return render_template('try3.html',
                           the_res = data_str,
                           male_data=df_male.to_html(classes="male", index=False),
                           the_select_region=regions_available)

@app.route('/get_user_info',methods=['GET', 'POST'])
# 视图函数
def get_user_info():
  # 调用读取数据的方法
    df = read_data()
    # 筛选数据目标（处理数据）
    df_animation = df.groupby(by=['行业', '城市']) \
    .agg({"企业名称": "count",\
          "估值（亿人民币）": ["sum", "mean"],\
          "成立年份": ["max", "min"], }) \
    .sort_values(by=[("估值（亿人民币）", "sum")], ascending=False) \
    .rename(columns={"sum": "总和", "mean": "均值", "count": "数量", "max": "最新", "min": "最早"})
    # 返回页面结果（变量名称 python文件中的变量 VS HTML文件中的变量）
    return render_template(
        "try4.html",
        # male_data、female_data 是HTML文件中的变量
        movies_data=df_animation.to_html(classes="企业名称")

    )
@app.route('/get')
def get():
    df = read_data()
    df.index.name = "序号"
    ds = pd.merge(df, \
                  df['部分投资机构'].str.split('[,,、]', expand=True) \
                  .stack().reset_index(level=1, drop=True).rename('部分投资机构(拆)'), \
                   on="序号")
    # ds = df_部分投资机构拆分[['企业名称', '部分投资机构(拆)', '估值（亿人民币）']] \
    #     .groupby(['部分投资机构(拆)']) \
    #     .agg({'企业名称': 'count', '估值（亿人民币）': 'sum'}) \
    #     .sort_values('估值（亿人民币）', ascending=False)


    df_head = df.head()
    df_invest = ds.head(7)

    return render_template(
        "try5.html",
        head_data=df_head.to_html(classes="head", index=False),
        invest_data=df_invest.to_html(classes="invest", index=False)
    )

@app.route('/hurun',methods=['POST'])
def hu_run_select() -> 'html':
    the_region = request.form["the_region_selected"]
    print(the_region) # 检查用户输入
    dfs = df.query("行业=='{}'".format(the_region))
    df_summary = dfs.groupby("城市").agg({"企业名称":"count","估值（亿人民币）":"sum","成立年份":"mean"}).sort_values(by = "企业名称",ascending = False )

    print(df_summary.head(5)) # 在后台检查描述性统计
    ## user select
    # print(dfs)
    # 交互式可视化画图
    fig = dfs.iplot(kind="bar", x="企业名称", y="估值（亿人民币）", asFigure=True)
    py.offline.plot(fig, filename="example.html",auto_open=False)
    with open("example.html", encoding="utf8", mode="r") as f:
        plot_all = "".join(f.readlines())

    # plotly.offline.plot(data, filename='file.html')
    data_str = dfs.to_html()
    return render_template('try3.html',
                            the_plot_all = plot_all,
                            the_res = data_str,
                            the_select_region=regions_available,
                           )





if __name__ == '__main__':
    app.run(debug=True)
